package com.jj.lib;

import android.os.Message;
import android.util.Log;

import com.jj.network.okhttp.BaseCallback;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/22.
 */

public abstract class DownloadCallback extends BaseCallback<String> {
    private WeakReference<MainActivity> mWeak;

    DownloadCallback(MainActivity activity) {
        mWeak = new WeakReference<MainActivity>(activity);
    }

    @Override
    protected String parsingData(Response response) {
        Log.e("dd", "==" + response.body().contentLength());
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            File dir = new File(mWeak.get().getExternalCacheDir().getAbsolutePath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            final File file = new File(dir, "kk.apk");
            fos = new FileOutputStream(file);
            int len;
            byte[] buf = new byte[1024*20];
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
            Log.e("dd", "==下载成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
